using Microsoft.AspNetCore.Mvc;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Api.Services;
using ProduceBasicData.ErrorCode;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// 编码生成控制器。
    /// - generate：根据规则生成编码并返回（不入库）。
    /// - assign：把编码写入指定记录的指定字段。
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CodeGeneratorController : ControllerBase
    {
        private readonly ICodeGeneratorService _service;
        public CodeGeneratorController(ICodeGeneratorService service)
        {
            _service = service;
        }

        /// <summary>
        /// 预生成编码（不落库）。
        /// 用于前端“编码预览/生成”，以便在保存前看到实际编码。
        /// </summary>
        [HttpPost("generate")]
        public async Task<ApiResult<GenerateCodeResponse>> Generate([FromBody] GenerateCodeRequest req)
        {
            if (!ModelState.IsValid)
            {
                return new ApiResult<GenerateCodeResponse> { Code = ApiEnum.Failed, Msg = "参数错误" };
            }
            var code = await _service.GenerateAsync(req);
            return new ApiResult<GenerateCodeResponse> { Code = ApiEnum.Success, Msg = "生成成功", Data = new GenerateCodeResponse { Code = code } };
        }

        /// <summary>
        /// 将编码写入实体指定字段并保存。
        /// 注意：该接口不会再次校验唯一性，通常在生成后立即调用即可。
        /// </summary>
        [HttpPost("assign")]
        public async Task<ApiResult<bool>> Assign([FromBody] AssignCodeRequest req)
        {
            if (!ModelState.IsValid)
            {
                return new ApiResult<bool> { Code = ApiEnum.Failed, Msg = "参数错误" };
            }
            var ok = await _service.AssignAsync(req);
            return new ApiResult<bool> { Code = ok ? ApiEnum.Success : ApiEnum.Failed, Msg = ok ? "写入成功" : "写入失败", Data = ok };
        }

        
    }
}


